<template>
  <view class="container">
    <template v-for="(group, index) in groupList" :key="index">
      <ve-card :title="group.title" v-if="searchList.length > 0" fold>
        <ve-form>
          <ve-form-item
            v-for="(item, index) in searchList.slice(group.start, group.end)"
            :key="item.prop"
            :label="item.label"
            :labelPosition="item.type == 'daterange-picker' ? 'top' : 'left'"
            v-show="!item.attrs || item.attrs.show !== false"
            :required="item?.attrs?.required"
          >
            <!-- text -->
            <view v-if="item.type == 'text' || item?.attrs?.disabled">
              {{ labelForm[item.prop] }}
            </view>
            <!-- picker -->
            <view v-else-if="item.type == 'picker'">
              <ve-picker-inline v-model="form[item.prop]" placeholder="请选择" :range="item.attrs.options" unit="arrowRight">
              </ve-picker-inline>
            </view>
            <!-- 时间选择 -->
            <view v-else-if="item.type == 'date-picker'">
              <ve-date-picker v-model="form[item.prop]"></ve-date-picker>
            </view>
            <!-- 时间周期选择 -->
            <view v-else-if="item.type == 'daterange-picker'" style="width: 100%">
              <ve-daterange-picker v-bind="item.attrs" v-model:start="form[item.prop[0]]" v-model:end="form[item.prop[1]]" />
            </view>
            <!-- 选择列表 -->
            <view v-else-if="item.type == 'remote-select'">
              <remote-select
                v-model="form[item.prop]"
                v-model:label="labelForm[item.prop]"
                :multiple="item.attrs.multiple"
                :type="item.attrs.type"
                :params="item.attrs.params"
                :config="item.config"
                :disabledValue="item.attrs.disabledValue"
                :required="item.attrs.required"
                :outData="item.attrs.outData"
                :title="item.attrs.title"
                @change="(val, options) => onChange(val, item, options)"
              ></remote-select>
            </view>
            <!-- radio -->
            <view v-else-if="item.type == 'radio'">
              <ve-radio v-model="form[item.prop]" :list="item.attrs.options" @confirm="onChange($event, item)"></ve-radio>
            </view>
            <!-- 数字输入框 -->
            <view v-else-if="item.type == 'input-number'">
              <ve-input type="digit" v-model.number="form[item.prop]" :placeholder="item.placeholder ? item.placeholder : '请输入'" />
            </view>
            <!-- 输入框 -->
            <view v-else>
              <ve-input v-model="form[item.prop]" :placeholder="item.placeholder ? item.placeholder : '请输入'" />
            </view>
          </ve-form-item>
        </ve-form>
        <div style="position: relative; margin-top: -3px; height: 5px; background: #fff; z-index: 9"></div>
      </ve-card>
    </template>

    <ve-bottom-box size="mini">
      <ve-button :customStyle="{ width: '238rpx', flex: 'inherit' }" @click="onReset">重置</ve-button>
      <ve-button type="primary" @click="onConfirm">确认筛选</ve-button>
    </ve-bottom-box>
  </view>
</template>

<script lang="ts" setup>
  import { onLoad } from '@dcloudio/uni-app'
  import { getCurrentInstance, nextTick, ref } from 'vue'
  const _this = getCurrentInstance().proxy
  import { cloneDeep } from '@/utils'

  // 在test.vue页面，向起始页通过事件传递数据
  const searchList = ref<any[]>([])
  const groupList = ref<any[]>([])
  const labelForm = ref({})
  const form = ref({})
  let eventChannel: any
  let filterData: any
  let searchList_initValue: any[] = []
  onLoad(async () => {
    uni.showLoading()
    await nextTick()
    if (!_this) return
    eventChannel = _this.getOpenerEventChannel()
    // 监听acceptDataFromOpenerPage事件，获取上一页面通过eventChannel传送到当前页面的数据
    eventChannel.on('acceptDataFromOpenerPage', (data: any) => {
      searchList_initValue = data.searchList
      filterData = {
        initData: data.initData,
        lastData: data.lastData,
        resetToInit: data.resetToInit,
      }
      initListAndData('playback')
      groupList.value = data.group || [{ start: 0, end: 999 }]
      nextTick(() => {
        uni.hideLoading()
      })
    })
  })
  // 提交
  const onConfirm = () => {
    let isRequired = false
    searchList.value.forEach((item: any) => {
      if (form.value[item.prop] === undefined && item.attrs?.required) {
        uni.showToast({
          title: `${item.label}必填`,
          icon: 'none',
        })
        isRequired = true
      }
      // 如果传入了 mustAll 代表需要同时选择开始时间和结束时间
      if (item.type == 'daterange-picker' && item.attrs?.mustAll) {
        const prop = item.prop
        const startTime = form.value[prop[0]]
        const endTime = form.value[prop[1]]
        if (startTime || endTime) {
          if (!startTime) {
            uni.showToast({
              title: '请选择开始时间',
              icon: 'none',
            })
            isRequired = true
          }
          if (!endTime) {
            uni.showToast({
              title: '请选择结束时间',
              icon: 'none',
            })
            isRequired = true
          }
        }
      }
    })
    if (isRequired) return
    eventChannel.emit('onConfirm', form.value, labelForm.value)
    uni.navigateBack()
  }
  // 初始化搜索列表
  const initListAndData = (mode = 'playback') => {
    // 1.重置搜索列表，复制chang方法，解决方法clone丢失
    searchList.value = cloneDeep(searchList_initValue)
    searchList.value.forEach((item: any, index: number) => {
      const init_item = searchList_initValue[index]
      if (init_item.attrs && init_item.attrs.change) {
        item.attrs.change = init_item.attrs.change
      }
      if (init_item.attrs && init_item.attrs.changeWithOption) {
        item.attrs.changeWithOption = init_item.attrs.changeWithOption
      }
    })
    // 2.初始化form值
    // 重置
    if (mode == 'playback') {
      form.value = cloneDeep(filterData.lastData.form)
      labelForm.value = cloneDeep(filterData.lastData.labelForm)
    } else {
      // 重置为空把searchList的prop置空；额外参数不修改 【重置为初始值false】
      if (filterData.resetToInit == false) {
        searchList_initValue.forEach((it: any) => {
          if (it.prop) {
            // 兼容数组（时间选择器）
            if (Array.isArray(it.prop)) {
              it.prop.forEach((prop_item: string) => {
                form.value[prop_item] = undefined
                labelForm.value[prop_item] = undefined
              })
            } else {
              form.value[it.prop] = undefined
              labelForm.value[it.prop] = undefined
            }
          }
        })
        return
      }
      form.value = cloneDeep(filterData.initData.form)
      labelForm.value = cloneDeep(filterData.initData.labelForm)
    }
  }
  // 重置
  const onReset = () => {
    // 触发change 重置级联 修改携带参数
    initListAndData('reset')
  }
  const onChange = (val: any, item: any, options?: any) => {
    if (item.attrs && item.attrs.change) {
      item.attrs.change(form, labelForm, searchList, val, options)
    }
    if (item.attrs && item.attrs.changeWithOption) {
      item.attrs.changeWithOption(val, options)
    }
  }
</script>

<style lang="less" scoped>
  .container {
    height: auto;
    min-height: 100%;
    padding: 24rpx 24rpx 24rpx;
  }
</style>
